﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.Lib;
using FBroSharp.Value;
using FBroSharp.Const;
using FBroSharp.DataType;
using System.IO;

namespace _2_多标签页浏览器
{
    public partial class Form1 : Form
    {
        private int _tabCounter = 0;
        private Dictionary<string, IFBroSharpBrowser> _browsers = new Dictionary<string, IFBroSharpBrowser>();
        
        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            // 创建第一个标签页
            CreateNewTab();
        }
        
        private void CreateNewTab()
        {
            _tabCounter++;
            string tabPageName = $"tab{_tabCounter}";
            string userFlag = $"browser{_tabCounter}";
            
            // 创建新的TabPage
            TabPage newTab = new TabPage($"新标签页 {_tabCounter}");
            newTab.Name = tabPageName;
            
            // 创建Panel用于承载浏览器
            Panel browserPanel = new Panel();
            browserPanel.Dock = DockStyle.Fill;
            browserPanel.Name = $"panel{tabPageName}";
            
            newTab.Controls.Add(browserPanel);
            tabControl1.TabPages.Add(newTab);
            
            // 创建浏览器实例
            CreateBrowserForTab(browserPanel, userFlag, tabPageName);
            
            // 切换到新标签页
            tabControl1.SelectedTab = newTab;
        }
        
        private void CreateBrowserForTab(Panel panel, string userFlag, string tabPageName)
        {
            // 创建窗口信息
            FBroSharpWindowsInfo windows_info = new FBroSharpWindowsInfo
            {
                parent_window = panel.Handle,
                x = 0,
                y = 0,
                width = panel.Width,
                height = panel.Height,
                window_name = $"浏览器标签页 {tabPageName}"
            };

            // 创建浏览器事件回调类
            BrowserEvent browser_event = new BrowserEvent(this, tabPageName);

            // 创建浏览器
            if (FBroSharpControl.CreatBrowser(
                "https://www.baidu.com", 
                windows_info, 
                default, 
                default, 
                default, 
                browser_event, 
                default, 
                userFlag))
            {
                Console.WriteLine($"标签页 {tabPageName} 浏览器创建成功");
            }
        }
        
        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateStatus), message);
                return;
            }
            
            toolStripStatusLabel1.Text = message;
        }
        
        public void UpdateUrlForTab(string tabPageName, string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string, string>(UpdateUrlForTab), tabPageName, url);
                return;
            }
            
            if (tabControl1.SelectedTab != null && tabControl1.SelectedTab.Name == tabPageName)
            {
                toolStripTextBox1.Text = url;
            }
        }
        
        public void UpdateTabTitle(string tabPageName, string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string, string>(UpdateTabTitle), tabPageName, title);
                return;
            }
            
            foreach (TabPage tab in tabControl1.TabPages)
            {
                if (tab.Name == tabPageName)
                {
                    tab.Text = title.Length > 20 ? title.Substring(0, 20) + "..." : title;
                    break;
                }
            }
        }
        
        public void UpdateNavigationButtons(string tabPageName, bool isLoading, bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string, bool, bool, bool>(UpdateNavigationButtons), tabPageName, isLoading, canGoBack, canGoForward);
                return;
            }
            
            if (tabControl1.SelectedTab != null && tabControl1.SelectedTab.Name == tabPageName)
            {
                toolStripButton2.Enabled = canGoBack;
                toolStripButton3.Enabled = canGoForward;
                toolStripButton4.Text = isLoading ? "停止" : "刷新";
            }
        }
        
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            CreateNewTab();
        }
        
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (tabControl1.TabPages.Count > 1)
            {
                TabPage currentTab = tabControl1.SelectedTab;
                if (currentTab != null)
                {
                    // 关闭浏览器实例
                    string userFlag = $"browser{currentTab.Name.Replace("tab", "")}";
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                    if (browser != null && browser.IsValid)
                    {
                        browser.CloseBrowser(true, true);
                    }
                    
                    // 移除TabPage
                    tabControl1.TabPages.Remove(currentTab);
                }
            }
            else
            {
                MessageBox.Show("至少需要保留一个标签页", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            NavigateBrowser("back");
        }
        
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            NavigateBrowser("forward");
        }
        
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            NavigateBrowser(toolStripButton4.Text == "刷新" ? "refresh" : "stop");
        }
        
        private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                NavigateBrowser("url", toolStripTextBox1.Text);
            }
        }
        
        private void NavigateBrowser(string action, string url = null)
        {
            if (tabControl1.SelectedTab == null) return;
            
            string tabPageName = tabControl1.SelectedTab.Name;
            string userFlag = $"browser{tabPageName.Replace("tab", "")}";
            var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
            
            if (browser == null || !browser.IsValid) return;
            
            switch (action)
            {
                case "back":
                    browser.GoBack();
                    break;
                case "forward":
                    browser.GoForward();
                    break;
                case "refresh":
                    browser.Reload();
                    break;
                case "stop":
                    browser.StopLoad();
                    break;
                case "url":
                    if (!string.IsNullOrEmpty(url))
                    {
                        // 确保URL有协议前缀
                        if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                        {
                            url = "https://" + url;
                        }
                        browser.GetMainFrame().LoadURL(url);
                    }
                    break;
            }
        }
        
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab != null)
            {
                string tabPageName = tabControl1.SelectedTab.Name;
                string userFlag = $"browser{tabPageName.Replace("tab", "")}";
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                
                if (browser != null && browser.IsValid)
                {
                    // 更新地址栏
                    toolStripTextBox1.Text = browser.GetMainFrame().GetURL();
                }
            }
        }
        
        private void Form1_Resize(object sender, EventArgs e)
        {
            // 调整所有标签页中的浏览器大小
            foreach (TabPage tab in tabControl1.TabPages)
            {
                string tabPageName = tab.Name;
                string userFlag = $"browser{tabPageName.Replace("tab", "")}";
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(userFlag);
                
                if (browser != null && browser.IsValid)
                {
                    Panel panel = tab.Controls[0] as Panel;
                    if (panel != null)
                    {
                        browser.MoveWindow(0, 0, panel.Width, panel.Height, true);
                    }
                }
            }
        }
    }
}